package com.ufgov.agcfs.baseData.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ufgov.agcfs.baseData.dao.AgcfsItemDao;
import com.ufgov.agcfs.baseData.entity.AgcfsSysItem;
import com.ufgov.agcfs.baseData.service.util.AgcfsItemUtil;
import com.ufgov.agcfs.pub.UUID;

import uap.iweb.entity.DataTable;
import uap.iweb.entity.Row;


@Transactional(propagation = Propagation.REQUIRED)
@Service
public class AgcfsItemService {
	@Autowired
	AgcfsItemDao agcfsItemDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	//获得查询条件
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public  <T> Map<String, Object> createSearchParamsStartingWith(String prefix,DataTable<T> dataTable1) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> m = dataTable1.getParams();
		Set<Entry<String, Object>> set = m.entrySet();
		for (Entry<String, Object> entry : set) {
			String key = entry.getKey();
			if (key.startsWith(prefix)) {
				String unprefixed = key.substring(prefix.length());
				params.put(unprefixed, entry.getValue().toString());
			}
		}
		return params;
	}
	
	//按年度查询
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<AgcfsSysItem> getItemByNd(String nd) {
		List<AgcfsSysItem> listAgcfsItem= agcfsItemDao.findByCode(nd);
		return listAgcfsItem;
	}

	//保存:先按年度删除，然后保存
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveItem(String nd,DataTable<AgcfsSysItem> reportItemDataTable) throws Exception{
		List<AgcfsSysItem> list=new ArrayList<AgcfsSysItem>();
		Row[] rows=reportItemDataTable.getAllRow();
		for (Row row : rows){
			AgcfsSysItem item=new AgcfsSysItem();
			item=reportItemDataTable.toBean(row);
			list.add(item);
		}

		//先删除
		AgcfsItemUtil util=new AgcfsItemUtil();
		util.deleteItemByNd(jdbcTemplate, nd);

		//插入
		util.insertItems(jdbcTemplate,list);
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveOneItem(AgcfsSysItem item, Map<String, String> resultMap)throws Exception{
		if ((item.getId()==null)||(item.getId().equals(""))) {	
			item.setId(UUID.randomUUID().toString());
			resultMap.put("id", item.getId());
			agcfsItemDao.insertReportItem(item);
		}else{
			agcfsItemDao.updateReportItem(item);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void deleteReportItem(AgcfsSysItem item,Map<String, String> resultMap)throws Exception{
		agcfsItemDao.delReportItem(item);
	}
}
